package com.sunmouse.toolkit.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.os.PowerManager;
import android.text.TextUtils;

import com.sunmouse.toollib.receiver.OnReceiveListener;
import com.sunmouse.toollib.utils.LogUtils;
import com.sunmouse.toolkit.receiver.CommandReceiver;
import com.sunmouse.toolkit.constant.Config;
import com.sunmouse.toolkit.constant.Value;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

public class AudioService extends Service implements MediaPlayer.OnErrorListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener, OnReceiveListener {

    private MediaPlayer mediaPlayer;
    private WifiManager.WifiLock mWifiLock;
    private CommandReceiver mReceiver;
    private Intent mIntent;
    private String currentFilePath;

    private Timer mTimer;
    private boolean isReleased = false;

    public AudioService() {

    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            currentFilePath = intent.getStringExtra(Config.Key.MEDIA);
            if (!TextUtils.isEmpty(currentFilePath))
                initMediaPlayer();
        }

        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * media player  initialization
     */
    private void initMediaPlayer() {
        isReleased = false;
        mReceiver = new CommandReceiver();
        registerReceiver(mReceiver, new IntentFilter(Value.Action.AUDIO_COMMAND));
        mReceiver.setOnReceiveListener(this);

        mWifiLock = ((WifiManager) getSystemService(WIFI_SERVICE))
                .createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");
        mWifiLock.acquire();

        mediaPlayer = new MediaPlayer();
        mediaPlayer.setWakeMode(this, PowerManager.PARTIAL_WAKE_LOCK);

        mediaPlayer.setOnPreparedListener(this);
        mediaPlayer.setOnCompletionListener(this);
        mediaPlayer.setOnErrorListener(this);


        try {
            mediaPlayer.setDataSource(currentFilePath);
            mediaPlayer.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        return false;
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        mp.start();
        mIntent = new Intent().setAction(Value.Action.AUDIO_PROGRESS);
        mIntent.putExtra(Config.Key.STATUS, Value.Status.PLAYING);
        sendBroadcast(mIntent);
        initTimer();

    }

    /**
     * init timer
     */
    private void initTimer() {
        mTimer = new Timer();
        mTimer.schedule(new ProgressTask(), 0, 1000);
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        mediaPlayer.pause();
        mediaPlayer.release();
        mediaPlayer = null;

        isReleased = true;


        sendStatus(Value.Status.STOP);

    }


    /**
     * progress task
     */
    class ProgressTask extends TimerTask {


        public ProgressTask() {
        }

        @Override
        public void run() {
            if (mediaPlayer == null || isReleased || !mediaPlayer.isPlaying()) return;
            mIntent = new Intent().setAction(Value.Action.AUDIO_PROGRESS);
            mIntent.putExtra(Config.Key.DURATION, mediaPlayer.getDuration());
            mIntent.putExtra(Config.Key.PROGRESS, mediaPlayer.getCurrentPosition());
            sendBroadcast(mIntent);
        }
    }


    @Override
    public void onDestroy() {
        unregisterReceiver(mReceiver);

        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }

        if (mWifiLock != null) {
            mWifiLock.release();
            mWifiLock = null;
        }

        releaseTimer();
        this.stopSelf();
        super.onDestroy();
    }

    /**
     * release timer
     */
    private void releaseTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent == null || !intent.getAction().equals(Value.Action.AUDIO_COMMAND)) return;
        int command = intent.getIntExtra(Config.Key.CONTROL, -1);
        if (mediaPlayer == null) initMediaPlayer();

        switch (command) {
            case Value.Control.PLAY:
                if (!mediaPlayer.isPlaying()) {
                    mediaPlayer.start();
                    sendStatus(Value.Status.PLAYING);
                }
                break;
            case Value.Control.PAUSE:
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.pause();
                    sendStatus(Value.Status.STOP);
                }
                break;
            case Value.Control.NEW_PROGRESS:
                LogUtils.d("-----------new progress---------");
                int progress = intent.getIntExtra(Config.Key.PROGRESS, -1);
                if (progress != -1 && mediaPlayer == null) {
                    progress = 0;
                    initMediaPlayer();
                }
                mediaPlayer.seekTo(progress * mediaPlayer.getDuration() / 100);
                mediaPlayer.start();
                break;
        }
    }

    /**
     * send status
     *
     * @param status
     */
    private void sendStatus(int status) {
        mIntent = new Intent().setAction(Value.Action.AUDIO_PROGRESS);
        mIntent.putExtra(Config.Key.STATUS, status);
        sendBroadcast(mIntent);
    }

}
